package com.fmync.ai.fmync.config;

import cn.hutool.core.util.StrUtil;
import lombok.Data;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.NestedConfigurationProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.task.AsyncTaskExecutor;
import org.springframework.core.task.support.ContextPropagatingTaskDecorator;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

@Data
@Configuration
@ConfigurationProperties(prefix = "langchain4j.ollama.streaming-chat-model.executor")
public class OllamaSystemProperties {
    private int corePoolSize;
    private int maxPoolSize;
    private int queueCapacity;
    private int keepAliveSeconds;
    private String threadNamePrefix;

    @Primary
    @Bean({"ollamaStreamingChatModelTaskExecutor"})
    @ConditionalOnProperty({"langchain4j.ollama.streaming-chat-model.base-url"})
    @ConditionalOnMissingBean(name = {"ollamaStreamingChatModelTaskExecutor"})
    AsyncTaskExecutor ollamaStreamingChatModelTaskExecutorWithContextPropagation() {
        ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
        taskExecutor.setCorePoolSize(corePoolSize); // 设置核心线程数
        taskExecutor.setMaxPoolSize(maxPoolSize); // 设置最大线程数
        taskExecutor.setQueueCapacity(queueCapacity); // 设置队列容量
        taskExecutor.setKeepAliveSeconds(keepAliveSeconds); // 设置线程空闲时间
        taskExecutor.setThreadNamePrefix(StrUtil.isBlank(threadNamePrefix)?"LangChain4j-Ollama-":threadNamePrefix);
        taskExecutor.setTaskDecorator(new ContextPropagatingTaskDecorator());
        taskExecutor.initialize();
        return taskExecutor;
    }

}
